<?php
namespace App\Services\Admin;

use App\Exceptions\AdminException;
use App\Http\Requests\Admin\LoginRequest;
use App\Managers\Admin\AdminUser\AdminUserManager;
use App\Models\ChatUserModel;
use App\Services\BaseService;
use App\Util\LoginUtil;
use Illuminate\Support\Facades\Cookie;


class IndexService extends BaseService
{
    public function __construct()
    {
        parent::__construct();

    }

    /**
     * 获取用户端token
     * @param int $user_id user表ID
     * @return array
     */
    public function getUserApiToken($user_id)
    {
        $token = auth('api')->tokenById($user_id);

        return [
            'access_token' => $token,
            'token_type' => 'bearer',
        ];
    }

    public function login(LoginRequest $request)
    {
        $request->authenticate();
        $userInfo =  auth('admin')->user();

        $user_id = data_get($userInfo, 'id');

        //检查账户是否禁用
        $is_valid = data_get($userInfo, 'is_valid');
        if ($is_valid == 0) {
            throw new AdminException('账号已禁用');
        }

        $token = auth('admin')->tokenById($user_id);
        Cookie::queue('token', $token, 1200,'/api/admin/');

        //登陆时间处理
        $this->loginTime($user_id,$userInfo);
        return [
            'access_token' => $token,
            'token_type' => 'bearer',
        ];
    }

    //注册
    public function register(LoginRequest $request)
    {
        $account = $request->input('account');
        $password = $request->input('password');
        if (empty($account)){
            throw new AdminException('账号不能为空');
        }
        if (empty($password) || strlen($password) < 6) {
            throw new AdminException('密码不能为空且长度至少为6位');
        }

        //判断账号是否存在
        $account_check = ChatUserModel::where('account',$account)->first();
        if ($account_check){
            throw new AdminException('账号已存在');
        }

        ChatUserModel::create([
            'account' => $request->input('account'),
            'password' => md5($request->input('password')),
            'phone' => $request->input('phone'),
            'email' => $request->input('email'),
            'nickname' => $request->input('nickname'),
        ]);
    }

    public function loginTime($user_id,$userInfo)
    {
      $ip = \request()->getClientIp();
      $data = [
          'last_login_time' =>data_get($userInfo, 'now_login_time',date('Y-m-d H:i:s')),
          'now_login_time' =>date('Y-m-d H:i:s'),
          'id' => $user_id,
          'last_login_ip'=>data_get($userInfo, 'now_login_ip',$ip),
          'now_login_ip' =>$ip

      ];


      app(AdminUserManager::class)->setData($data)->save();
    }

}
